package top.yqingyu.trans$client.cs.command.impl;

import lombok.extern.slf4j.Slf4j;
import top.yqingyu.common.utils.IoUtil;
import top.yqingyu.common.utils.ThreadUtil;
import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.trans$client.common.TransSocket;
import top.yqingyu.trans$client.cs.command.Command;
import top.yqingyu.trans$client.main.TransClient;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.transclient.sc.command.impl.Forward
 * @description
 * @createTime 2022年07月23日 18:00:00
 */

@Slf4j
public class Forward extends Command {

    private static final String commandRegx = "^(forward).*$";
    private static final ThreadPoolExecutor IO_POOL = ThreadUtil.createQyFixedThreadPool(2, "trans", null);

    @Override
    public void deal(QyMsg msg, TransClient client) throws Exception {

        if (MsgHelper.gainMsg(msg).matches("^(forward)" +
                "(" + "( ){1,5}" + "(" + "((-)(s|stream))" + "(( ){1,5})([\\w]{8}(-))((([\\w]{4})(-)){3})([\\w]{12})" +          //客户端id
                "(( ){1,5})((6[0-4][\\d]{3})|(65[0-4][\\d]{2})|(655[0-2][\\d])|(6553[0-5])|([1-5][\\d]{4})|([\\d]{0,4}))" +   //端口号
                "(( ){1,5})((6[0-4][\\d]{3})|(65[0-4][\\d]{2})|(655[0-2][\\d])|(6553[0-5])|([1-5][\\d]{4})|([\\d]{0,4}))))")) {
            String[] msgSplit = MsgHelper.gainMsg(msg).split(" ");

            Socket proxy = TransSocket.getTransSocket(client, client.clientConf.HOST, client.clientConf.PORT);

            if (proxy != null && proxy.isConnected()) {
                String port = msgSplit[4];

                AtomicReference<Socket> A_transSocket = new AtomicReference<>();
                FutureTask<Socket> task = new FutureTask<>(() -> {
                    ServerSocket serverSocket = new ServerSocket(Integer.parseInt(port));
                    A_transSocket.set(serverSocket.accept());
                    return A_transSocket.get();
                });
                new Thread(task).start();
                Socket transSocket = task.get(2, TimeUnit.MINUTES);

                //待socket准备完成，开始转发
                IoUtil.transSocket(transSocket, proxy, IO_POOL, 1024);

            }
        } else if (MsgHelper.gainMsg(msg).matches("^(forward)( ){1,5}(-)(stop)")) {
            IO_POOL.shutdown();
        }


    }
}
